package com.sinopec.basemodule.utils;

import androidx.annotation.WorkerThread;

import com.github.promeg.pinyinhelper.Pinyin;
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict;
import com.google.gson.Gson;
import com.sinopec.basemodule.BaseApplication;
import com.sinopec.basemodule.common.Logger;
import com.sinopec.basemodule.model.ProvinceCityModel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

import okhttp3.ResponseBody;

/**
 * 类描述：省市区工具类<br/>
 * 创建人：lwj<br/>
 * 创建时间：2019/6/14 20:01 <br/>
 */
public class ProvinceCityUtils {
    private static ProvinceCityModel model;
    /**
     * 文件路径
     */
    private static final String FILE_DIR = BaseApplication.getInstance().getApplicationContext().getFilesDir().getAbsolutePath();
    /**
     * 省市区保存文件文件名
     */
    private static final String NAME = "province_city.json";

    public static final String ALL_NAME = FILE_DIR + File.separator + NAME;

    private ProvinceCityUtils() {
    }

    /**
     * 保存文件
     */
    //@RequiresPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    @WorkerThread
    public static String saveFile(ResponseBody body) {
        String path = ALL_NAME;
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            File templateJsonFile = new File(path);
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(templateJsonFile);

                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                    Logger.d("file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                outputStream.flush();
                model = null;
                return path;
            } catch (IOException e) {
                Logger.e(e.getMessage());
                return null;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            Logger.e(e.getMessage());
            return null;
        }
    }

    /**
     * 读取文件
     */
    //@RequiresPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
    @WorkerThread
    public static ProvinceCityModel readFile() {
        if (model == null) {
            // 添加中文城市词典
            Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(BaseApplication.getInstance().getApplicationContext())));
            try {
                model = new Gson().fromJson(new FileReader(ALL_NAME), ProvinceCityModel.class);
            } catch (Exception e) {
                try {
                    model = new Gson().fromJson(new InputStreamReader(BaseApplication.getInstance().getAssets().open(NAME), StandardCharsets.UTF_8), ProvinceCityModel.class);
                } catch (Exception e1) {
                    return null;
                }
                //排序数据
                sortModelData();
                return model.clone();
            }
            //排序数据
            sortModelData();
        }
        return model.clone();
    }

    private static void sortModelData() {
        //省数据
        List<ProvinceCityModel> provinceModelList = model.getSubjections();
        for (ProvinceCityModel provinceModel : provinceModelList) {
            //省中对应市数据
            List<ProvinceCityModel> cityModelList = provinceModel.getSubjections();
            for (ProvinceCityModel cityModel : cityModelList) {
                List<ProvinceCityModel> areaModelList = cityModel.getSubjections();
                for (ProvinceCityModel areaModel : areaModelList) {
                    areaModel.setPinyin(Pinyin.toPinyin(areaModel.getName(), ""));
                }
                //排序区
                Collections.sort(areaModelList);
                cityModel.setPinyin(Pinyin.toPinyin(cityModel.getName(), ""));
            }
            //排序城市
            Collections.sort(cityModelList);
            provinceModel.setPinyin(Pinyin.toPinyin(provinceModel.getName(), ""));
        }
        //排序省
        Collections.sort(provinceModelList);
    }
}